<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>数据源</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body style="padding: 20px 10px;">

<!-- 你的 HTML 代码 -->
<div class="demoTable">
    数据源：
    <div class="layui-inline">
        <input class="layui-input" placeholder="搜索数据源" name="name" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" id="demoReloadBtn">搜索</button>
    <a href="user.html" class="layui-btn">用户列表</a>
    <a href="request_log.html" class="layui-btn">请求日志</a>
    <button type="button" class="layui-btn" id="reportBtn">报告</button>
</div>
<table id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="connect">测试</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="config">管理接口</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加数据源</button>
    </div>
</script>
<form class="layui-form" lay-filter="formTest" action="" id="addDataSource" style="display:none;width: 500px;padding: 20px;">
    <div class="layui-form-item">
        <label class="layui-form-label">连接名</label>
        <div class="layui-input-block">
            <input type="text" name="name" required  lay-verify="required" placeholder="请输入连接名" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">类型</label>
        <div class="layui-input-block">
            <select name="type" lay-verify="required" lay-filter="type">
                <option value="mysql">mysql</option>
                <option value="oracle">oracle</option>
                <option value="sqlserver">sqlserver</option>
                <option value="postgresql">postgresql</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">主机名</label>
        <div class="layui-input-block">
            <input type="text" name="host" required  lay-verify="required" placeholder="请输入主机名" autocomplete="off" class="layui-input" value="127.0.0.1">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">端口</label>
        <div class="layui-input-block">
            <input type="text" name="port" required  lay-verify="required|number" placeholder="请输入端口号" autocomplete="off" class="layui-input" value="3306">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数据库名称</label>
        <div class="layui-input-block">
            <input type="text" name="dbname" required  lay-verify="required" placeholder="请输入数据库名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-block">
            <input type="text" name="username" required  lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" required  lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-danger" id="connectBtn">连接测试</button>
            <button class="layui-btn" lay-submit lay-filter="formDemo">确定</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script src="./layui/layui.js"></script>
<script>
layui.use(['element', 'layer', 'form', 'table', 'jquery'], function(){
  var layer = layui.layer;
  var table = layui.table;
  var form = layui.form;
  var $ = layui.$;

  window.connectDb = function(data){
    $.ajax({
        type: "POST",
        url: "/data-source-info/connect",
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0 && result.data) {
                layer.msg('连接成功', {icon: 6})
            } else {
                layer.msg('连接失败', {icon: 5});
            }
        }
    });
  };

   //第一个实例
  var tableData = [];
  table.render({
    elem: '#demo'
    ,toolbar: '#toolbarDemo'

    ,url: '/data-source-info/findPage' //数据接口
    ,method: 'post'
    ,request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
    }
    ,page: true //开启分页
    ,where: {}
    ,headers: {}
    ,done: function(res, curr, count){
        tableData = res.data;
    }
    ,parseData: function(res){ //res 即为原始返回的数据
        return {
          "code": res.code, //解析接口状态
          "msg": res.msg, //解析提示文本
          "count": res.data.total, //解析数据长度
          "data": res.data.list //解析数据列表
        };
    }
    ,response: {
        statusName: 'code' //规定数据状态的字段名称，默认：code
        ,statusCode: '0000' //规定成功的状态码，默认：0
        ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
        ,countName: 'count' //规定数据总数的字段名称，默认：count
        ,dataName: 'data' //规定数据列表的字段名称，默认：data
    }
    ,contentType: 'application/json'
    ,cols: [[ //表头
      {field: 'id', title: '序号', type: 'numbers', width:80, fixed: 'left'}
      ,{field: 'name', title: '连接名', edit: 'text'}
      ,{field: 'type', title: '类型'}
      ,{field: 'host', title: '主机名', edit: 'text'}
      ,{field: 'port', title: '端口', edit: 'text'}
      ,{field: 'dbname', title: '数据库名称', edit: 'text'}
      ,{field: 'username', title: '用户名', edit: 'text'}
      ,{field: 'password', title: '密码', edit: 'text'}
      ,{fixed: 'right', title: '操作', width:220, align:'center', toolbar: '#barDemo'}
    ]]
  });

  //触发事件
    table.on('toolbar(test)', function(obj){
      switch(obj.event){
        case 'add':
            layer.open({
              type: 1,
              title: '添加数据源',
              area: '600px',
              content: $('#addDataSource') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        break;
      };
    });

    form.on('select(type)', function(data){
        var port = 0;
        switch(data.value) {
         case "mysql":
            port = 3306;
            break;
         case "oracle":
            port = 1521;
            break;
         case "sqlserver":
            port = 1433;
            break;
         case "postgresql":
            port = 5432;
            break;
        }
        form.val("formTest", {
          "port": port
        });
    });

    //工具条事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data; //获得当前行数据
      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

      if(layEvent === 'connect'){ //测试
        //do somehing
        connectDb(data);
      } else if(layEvent === 'del'){ //删除
        if(!data.id){
            obj.del();
            return false;
        }
        layer.confirm('确认删除数据源吗', function(index){
          layer.close(index);
          //向服务端发送删除指令
          $.ajax({
            type: "POST",
            url: "/data-source-info/deleteById",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('删除成功', {icon: 6})
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        });
      } else if(layEvent === 'config'){ // 管理接口
        if(!data.id){
            return false;
        }
        window.location.href = '/interface.html?dataSourceId=' + data.id;
      } else if(layEvent === 'LAYTABLE_TIPS'){
        layer.alert('Hi，头部工具栏扩展的右侧图标。');
      }
    });

    table.on('edit(test)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
      if (obj.field == "port" && !(/(^[1-9]\d*$)/.test(obj.value))) {
　　　　　　layer.alert('请输入正确的端口号');
　　　　　　return false;
　　　 }
      $.ajax({
        type: "POST",
        url: "/data-source-info/save",
        data: JSON.stringify(obj.data),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                layer.msg('保存成功', {icon: 6})
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
      });
    });

    //监听提交
  form.on('submit(formDemo)', function(data){
    $.ajax({
        type: "POST",
        url: "/data-source-info/save",
        data: JSON.stringify(data.field),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                window.location.reload();
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
    });
    return false;
  });

  $("#demoReloadBtn").click(function(){
    var name = $("#demoReload").val();
    table.reload('demo', {where: {queryModel: {name: name}}}, true);
  });

  $("#connectBtn").click(function(){
    var data = form.val("formTest");
    connectDb(data);
  });

  window.formatNumber = function(num) {
    if(isNaN(num)){
        return 0;
    }
    return Number(num).toLocaleString();
  };

  $.ajax({
        type: "GET",
        url: "/report/info",
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                var data = result.data;
                $("#reportBtn").hover(function(){
                    var content = "数据源：" + formatNumber(data.datasourceCount) +
                    "<br>接口：" + formatNumber(data.interfaceCount) +
                    "<br>用户：" + formatNumber(data.userCount) +
                    "<br>调用次数：" + formatNumber(data.requestCount) +
                    "<br>开放接口：" + formatNumber(data.openApiCount);
                    layer.tips(content, this, {time: 0});
                },function(){
                    layer.closeAll('tips');
                });
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
    });
});
</script>
</body>
</html>